package cn.lizhangqu.kb.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;

import java.io.UnsupportedEncodingException;
import java.util.List;

import cn.lizhangqu.kb.R;
import cn.lizhangqu.kb.adapter.MenuAdapter;
import cn.lizhangqu.kb.model.LinkNode;
import cn.lizhangqu.kb.service.CourseService;
import cn.lizhangqu.kb.service.LinkService;
import cn.lizhangqu.kb.service.ScoreService;
import cn.lizhangqu.kb.util.CommonUtil;
import cn.lizhangqu.kb.util.HttpUtil;
import cn.lizhangqu.kb.util.HttpUtil.QueryCallback;
import cn.lizhangqu.kb.util.LinkUtil;
import cn.lizhangqu.kb.util.SharedPreferenceUtil;
import cn.lizhangqu.kb.util.Toasts;

/**
 * @author lizhangqu
 * @date 2015-2-1
 */
public class MainActivity extends Activity {

	private GridView gridView;
	private LinkService linkService;
	private CourseService courseService;
	private ScoreService scoreService;
	private String code;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initValue();// 变量初始化
		initView();// 视图初始话
		initEvent();// 事件初始化

	}

	/**
	 * 初始化变量
	 */
	private void initValue() {
		linkService = LinkService.getLinkService();
		courseService = CourseService.getCourseService();
		scoreService = ScoreService.getScoreService();
	}

	/**
	 * 初始化View
	 */
	private void initView() {
		gridView = (GridView) findViewById(R.id.gridview);
		List<LinkNode> objects = linkService.findAll();
		gridView.setAdapter(new MenuAdapter(getApplicationContext(), R.layout.item_linknode_layout, objects));
	}

	/**
	 * 初始事件
	 */
	private void initEvent() {
		// 一系列点击事件的初始化
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				TextView temp = (TextView) view.findViewById(R.id.title);
				String title = temp.getText().toString();
				if (title.equals(LinkUtil.XSGRKB)) {
					jump2Kb(false);
				}
				if (title.equals(LinkUtil.CJCX)) {
					jump2cj(false);
				} else {
					Toasts.makeText(title);
				}
			}
		});
	}

	private void jump2cj(boolean flag) {
		SharedPreferenceUtil util = new SharedPreferenceUtil(getApplicationContext(), "scoreFlag");
		if (flag) {
			//true证明已经获取过，直接跳转
			util.setKeyData(LinkUtil.CJCX, "TRUE");
			CommonUtil.jump2Intent(this, ScoreActivity.class);
		} else {

			String keyData = util.getKeyData(LinkUtil.CJCX);
			if (keyData.equals("TRUE")) {
				CommonUtil.jump2Intent(this, ScoreActivity.class);
			} else {
				//未获取则获取
				HttpUtil.getQuery(MainActivity.this, linkService, LinkUtil.CJCX, new QueryCallback() {
					@Override
					public String handleResult(byte[] result) {
						Log.d("xxxx", "开始获取成绩。。。。");
						try {
							code = scoreService.parseScoreCode(new String(result, "gb2312"));
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
						getScoreData(code);
						return null;
					}
				});

			}
		}



//			private void getDate(String code) {
//				RequestParams params = new RequestParams();
//				params.add("Button1", "按学期查询");
//				params.add("__VIEWSTATE", code);
//				HttpUtil.post(HttpUtil.URL_BASE + "xscj_gc.aspx?xh=1421145116&xm=柯尊诚&gnmkdm=N121605"
//						, params, new AsyncHttpResponseHandler() {
//					@Override
//					public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//						Toast.makeText(MainActivity.this, "获取成功！！！", Toast.LENGTH_LONG)
//								.show();
//						String ret = null;
//
//						try {
//							ret = scoreService.parseScore(new String(responseBody, "gb2312"));
//						} catch (UnsupportedEncodingException e) {
//							e.printStackTrace();
//						}
//						Intent intent = new Intent(MainActivity.this, ScoreActivity.class);
////						intent.putExtra("result", ret);
//						startActivity(intent);
//
//
//					}
//
//					@Override
//					public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//						Toast.makeText(MainActivity.this, "获取失败！！！", Toast.LENGTH_LONG)
//								.show();
//					}
//				});
//
//			}



	}



	private void getScoreData(String code) {
		HttpUtil.getQueryDate(MainActivity.this, linkService, LinkUtil.CJCX, code, new QueryCallback() {

			@Override
			public String handleResult(byte[] result) {
				try {
					scoreService.parseScore(new String(result, "gb2312"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				jump2cj(true);
				return null;
			}
		});
	}


	/**
	 * 跳到课表页面
	 */
	private void jump2Kb(boolean flag) {
		SharedPreferenceUtil util = new SharedPreferenceUtil(getApplicationContext(), "flag");
		if (flag) {
			//flag为true直接跳转
			util.setKeyData(LinkUtil.XSGRKB, "TRUE");
			Intent intent = new Intent(MainActivity.this, CourseActivity.class);
			startActivity(intent);
		} else {
			//flag为false，则先判断是否获取过课表
			//如果已经获取过课表，则跳转
			String keyData = util.getKeyData(LinkUtil.XSGRKB);
			if (keyData.equals("TRUE")) {
				Intent intent = new Intent(MainActivity.this,CourseActivity.class);
				startActivity(intent);
			} else {
				//未获取则获取
				HttpUtil.getQuery(MainActivity.this, linkService,LinkUtil.XSGRKB, new QueryCallback() {
					@Override
					public String handleResult(byte[] result) {
						Log.d("xxxx", "开始获取。。。。");
						String ret=null;

						try {
//							Log.d("xxxx", new String(result,"gb2312"));
//							Intent intent = new Intent(MainActivity.this, TextActivity.class);
//							intent.putExtra("text", new String(result,"gb2312"));
//							startActivity(intent);
//							finish();
							ret = courseService.parseCourse(new String(result,"gb2312"));
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
//						Log.d("xxxx", ret);
						jump2Kb(true);
						return ret;
					}
				});
			}
		}

	}
}
